package com.example.devtool.db.util;

import com.example.devtool.db.consts.DbTypeEnum;
import com.example.devtool.db.model.DbModel;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.ResultSet;

/**
 * @author zhuliangxuan
 * @date 2022/5/21 22:22
 * 数据库工具类
 */
public class DbUtil {
    private static String sqlFormat = "jdbc:%s://%s:%d/%s?characterEncoding=utf-8&useSSL=false&useTimezone=true";

    public static void main(String[] args) throws Exception {
        DbModel dbModel = new DbModel();
        dbModel.setCode(DbTypeEnum.MARIADB.getCode());
        dbModel.setHost("127.0.0.1");
        dbModel.setPort(3306);
        dbModel.setUsername("root");
        dbModel.setPassword("zhu123456");
        dbModel.setSchema("generate");
        DataSource dataSource = getDataSource(dbModel);
        ResultSet resultSet = dataSource.getConnection().getMetaData().getCatalogs();
        while (resultSet.next()) {
            String s = resultSet.getString(1);
            System.out.println(s);
        }
    }

    private static DataSource getDataSource(DbModel dbModel) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(buildJdbcUrl(dbModel));
        config.setUsername(dbModel.getUsername());
        config.setPassword(dbModel.getPassword());
        config.addDataSourceProperty("connectionTimeout", "1000"); // 连接超时：1秒
        config.addDataSourceProperty("idleTimeout", "60000"); // 空闲超时：60秒
        config.addDataSourceProperty("maximumPoolSize", "10"); // 最大连接数：10
        return new HikariDataSource(config);
    }

    private static String buildJdbcUrl(DbModel dbmodel) {
        DbTypeEnum dbTypeEnum = DbTypeEnum.getFromCode(dbmodel.getCode());
        return String.format(sqlFormat, dbTypeEnum.getType(), dbmodel.getHost(), dbmodel.getPort(), dbmodel.getSchema())+"&serverTimezone=GMT%2B8";
    }
}
